#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import threading
import sys
import time
import logging
from env import sysConf
import socket
import json
import traceback
logger = logging.getLogger(__name__)


def do_command(cmd):
    """ 执行终端命令并返回文本结果 """
    output = os.popen(cmd)
    return output.read()


class clientProgress(threading.Thread):
    """
    客户端线程类，TCP连接空明服务端
    """

    def __init__(self):
        threading.Thread.__init__(self)
        self.running = True
        self.__uuid = None

    def exitProcess(self):
        self.running = False
        logger.error("exitProcess")

    def do_login(self):
        """ 登录到服务器 """
        build = json.dumps({
            "cmd": "login",
            "timestamp": int(time.time()),
            "sn": sysConf["sn"]
        })
        self.__socket.send(build.encode("utf-8"))

    def on_message(self):
        """ 处理消息 """
        while True:
            try:
                buffer = self.__socket.recv(1024).decode(encoding="utf8")
                obj = json.loads(buffer)
                logger.info(obj)
                if obj.get('uuid'):
                    self.__uuid = obj['uuid']
                elif obj.get('cmd') == 'ssh':
                    try:
                        command = obj.get('command')
                        # 执行命令 返回给服务器
                        r = do_command(command)
                        logging.info(r)
                        self.__socket.send(r.encode("utf-8"))
                    except Exception as e:
                        logging.error(e)

                elif obj.get('cmd') == 'reboot':
                    do_command(command)
            except Exception as e:
                logger.error(e)
                raise


    def heartbeat(self):
        """ 服务器心跳  保持3秒1次"""
        while True:
            try:
                if self.__uuid:
                    build_text = json.dumps({
                        "cmd": "heartbeat",
                        "timestamp": int(time.time()),
                        "sn": sysConf["sn"],
                        "uuid": self.__uuid
                    })
                    self.__socket.send(build_text.encode("utf-8"))
            except:
                # self.do_login()
                logger.error("服务器连接失败")
                break
            time.sleep(3)

    def run(self):
        logger.info("clientprogress running ...")
        while self.running:
            try:
                self.__socket = socket.socket(socket.AF_INET,
                                              socket.SOCK_STREAM)
                self.__socket.connect(
                    (sysConf[u"service_host"], sysConf[u"service_port"]))
                self.do_login()
                threading.Thread(target=self.heartbeat,
                                 args=(),
                                 name="heartbeat").start()
                self.on_message()
            except:
                logger.error(traceback.format_exc())
            callable
